<template>
  <div class="game-container">
    <div class="score-bar">
      <div :style="{ width: `${(score / 200) * 100}%` }" class="progress"></div>
    </div>
    <div v-for="(row, rowIndex) in grid" :key="rowIndex" class="row">
      <div v-for="(cell, cellIndex) in row" :key="cellIndex" class="cell" @click="handleClick(rowIndex, cellIndex)">
        <img :src="getCellImage(cell)" v-if="cell" alt="Color Block" class="block-image" />
      </div>
    </div>
    <p>当前积分: {{ score }} / 200</p>
    <p v-if="score < 200">还差 {{ 200 - score }} 分满200</p>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';

const COLORS = ['red', 'blue'];
const grid = ref([]);
const isFlashing = ref(false);
const score = ref(0);

const initGrid = () => {
  const newGrid = [];
  for (let i = 0; i < 8; i++) {
    newGrid.push(Array(8).fill(null).map(() => COLORS[Math.floor(Math.random() * COLORS.length)]));
  }
  grid.value = newGrid;
};

const handleClick = (row, col) => {
  if (grid.value[row][col]) {
    eliminate(row, col);
    fillEmptySpaces();
    checkForEliminatableBlocks();
  }
};

const eliminate = (row, col) => {
  const color = grid.value[row][col];

  // 检查是否有相邻的相同颜色的色块
  if (!hasAdjacentSameColor(row, col, color)) return;

  const toEliminate = [[row, col]];
  const visited = Array.from({ length: 8 }, () => Array(8).fill(false));

  const dfs = (r, c) => {
    if (r < 0 || r >= 8 || c < 0 || c >= 8 || visited[r][c] || grid.value[r][c] !== color) return;
    visited[r][c] = true;
    toEliminate.push([r, c]);
    dfs(r - 1, c); // 上
    dfs(r + 1, c); // 下
    dfs(r, c - 1); // 左
    dfs(r, c + 1); // 右
  };

  dfs(row, col);

  // 如果只有一个元素，则不进行消除
  if (toEliminate.length <= 1) return;

  toEliminate.forEach(([r, c]) => (grid.value[r][c] = null));

  // 更新积分
  updateScore(toEliminate.length);
};

const updateScore = (eliminatedCount) => {
  let points = eliminatedCount * 1; // 每个消除的色块得1分

  // 根据消除的色块数量进行翻倍
  if (eliminatedCount > 1) {
    points *= 2; // 消除的色块数量大于1时，积分翻倍
  }

  score.value += points;

  if (score.value >= 200) {
    // alert('恭喜你！积分达到200分！');
    score.value = 0;
  }
};

const fillEmptySpaces = () => {
  // 处理垂直方向的下落
  for (let col = 0; col < 8; col++) {
    let emptyCount = 0;
    for (let row = 7; row >= 0; row--) {
      if (grid.value[row][col] === null) {
        emptyCount++;
      } else if (emptyCount > 0) {
        [grid.value[row + emptyCount][col], grid.value[row][col]] = [grid.value[row][col], null];
      }
    }
  }

  // 处理水平方向的左移
  for (let row = 0; row < 8; row++) {
    let emptyCount = 0;
    for (let col = 0; col < 8; col++) {
      if (grid.value[row][col] === null) {
        emptyCount++;
      } else if (emptyCount > 0) {
        [grid.value[row][col - emptyCount], grid.value[row][col]] = [grid.value[row][col], null];
      }
    }
  }
};

const checkForEliminatableBlocks = () => {
  let hasEliminatableBlocks = false;

  for (let row = 0; row < 8; row++) {
    for (let col = 0; col < 8; col++) {
      if (grid.value[row][col]) {
        const color = grid.value[row][col];
        const toEliminate = [[row, col]];
        const visited = Array.from({ length: 8 }, () => Array(8).fill(false));

        const dfs = (r, c) => {
          if (r < 0 || r >= 8 || c < 0 || c >= 8 || visited[r][c] || grid.value[r][c] !== color) return;
          visited[r][c] = true;
          toEliminate.push([r, c]);
          dfs(r - 1, c); // 上
          dfs(r + 1, c); // 下
          dfs(r, c - 1); // 左
          dfs(r, c + 1); // 右
        };

        dfs(row, col);

        if (toEliminate.length > 1) {
          hasEliminatableBlocks = true;
          return; // 存在可消除的色块，直接返回
        }
      }
    }
  }

  if (!hasEliminatableBlocks) {
    console.log("没有可以消除的色块");
    // 重新生成
    initGrid();
    // startFlashAnimation();
  }
};

const startFlashAnimation = () => {
  isFlashing.value = true;

  setTimeout(() => {
    isFlashing.value = false;
    alert('没有更多可以消除的色块');
  }, 3000);
};

const hasAdjacentSameColor = (row, col, color) => {
  const directions = [
    [-1, 0], // 上
    [1, 0], // 下
    [0, -1], // 左
    [0, 1] // 右
  ];

  for (const [dr, dc] of directions) {
    const newRow = row + dr;
    const newCol = col + dc;
    if (newRow >= 0 && newRow < 8 && newCol >= 0 && newCol < 8 && grid.value[newRow][newCol] === color) {
      return true;
    }
  }

  return false;
};

const getCellImage = (color) => {
  if (color === 'red') {
    return '/static/icon1.png';
  } else if (color === 'blue') {
    return '/static/icon2.png';
  }
  return '';
};

onMounted(() => {
  initGrid();
});
</script>

<style scoped>
.game-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.score-bar {
  width: 100%;
  height: 20px;
  background-color: #e0e0e0;
  border: 1px solid #ccc;
  margin-bottom: 10px;
  position: relative;
}

.progress {
  height: 100%;
  background-color: #4caf50;
  transition: width 0.5s;
}

.row {
  display: flex;
}

.cell {
  width: 50px;
  height: 50px;
  margin: 2px;
  position: relative;
}

.block-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.flash {
  animation: flash 1s infinite;
}

@keyframes flash {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.2;
  }

  100% {
    opacity: 1;
  }
}
</style>